package com.jjx.trainingapi.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjx.trainingapi.entity.po.DcCourse;
import com.jjx.trainingapi.entity.po.QuestionItem;
import com.jjx.trainingapi.entity.po.UserRecord;
import com.jjx.trainingapi.entity.po.UserRecordError;
import com.jjx.trainingapi.entity.vo.DoAnswerVo;
import com.jjx.trainingapi.mapper.QuestionItemMapper;
import com.jjx.trainingapi.service.QuestionItemService;
import com.jjx.trainingapi.service.UserRecordErrorService;
import com.jjx.trainingapi.service.UserRecordService;
import com.jjx.trainingapi.util.LoginManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author LoveHuahua
 * @date 2022年05月24日 1:10
 * @description believe in yourself
 */
@Service
public class QuestionItemServiceImpl extends ServiceImpl<QuestionItemMapper, QuestionItem> implements QuestionItemService {
    @Autowired
    private UserRecordErrorService errorService;
    @Autowired
    private  UserRecordService userRecordService;

    /**
     * 答案提交接口
     *
     * @param questionItem
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DoAnswerVo doAnswer(QuestionItem questionItem) {
        Integer id = questionItem.getId();
        //题目
        QuestionItem question = getById(id);
        //保存记录
        UserRecord userRecord = new UserRecord();
        userRecord.setUserId(LoginManager.getUserId());
        userRecord.setQuestionItemId(id);
        userRecord.setResult((question.getAnswer().equals(questionItem.getAnswer()) ? 1 : 0));
        userRecordService.save(userRecord);

        if (question.getAnswer().equals(questionItem.getAnswer())) {
            DoAnswerVo doAnswerVo = new DoAnswerVo();
            doAnswerVo.setResult(true);
            return doAnswerVo;
        }
        //查询是否存在错误记录
        UserRecordError error = errorService.getOne(Wrappers.<UserRecordError>query().lambda().eq(UserRecordError::getUserId, LoginManager.getUserId()).eq(UserRecordError::getQuestionItemId, id));
        if (error == null){
            //错误记录
            UserRecordError entity = new UserRecordError();
            entity.setUserId(LoginManager.getUserId());
            entity.setQuestionItemId(id);
            //用户选择的错误选项
            entity.setAnswer(questionItem.getAnswer());
            errorService.save(entity);
        }

        DoAnswerVo doAnswerVo = new DoAnswerVo();
        doAnswerVo.setResult(false);
        return doAnswerVo;
    }

    /**
     * 获取错题
     *
     * @param questionItem
     * @return
     */
    @Override
    public List<QuestionItem> getErrorQuestion(DcCourse questionItem) {
        return baseMapper.getErrorQuestion(questionItem.getId(),LoginManager.getUserId());
    }
}

